var taskId = "0";
console.log(taskId);
// const baseUrl = [[${#servletContext.contextPath}]];
console.log(baseUrl);
var editTableRowObj = null;
var selTaskSourceList= []; //任务选择的数据详情 -- type:类型，list:号码数据/选择的条件
var clickSubmit = false;//是否点击了保存
var SelTaskSource = {
    buildParam:function (type,param) {
        var selTaskSourceObj = {};
        selTaskSourceObj.type = type;
        selTaskSourceObj.param  = param;
        return selTaskSourceObj;
    }
};
layui.use(['form','layer','layedit','laydate','upload','table','element'],function(){
    var form = layui.form,
        layer = layui.layer,
        laypage = layui.laypage,
        upload = layui.upload,
        layedit = layui.layedit,
        laydate = layui.laydate,
        $ = layui.jquery;
    table = layui.table;
    element = layui.element;
    //列表
    //转换静态表格
    table.init('taskList', {
        height: 250 //设置高度
        ,limit: 10 //注意：请务必确保 limit 参数（默认：10）是与你服务端限定的数据条数一致
        //支持所有基础参数
    });
   var tableIns = table.render({
        elem: '#taskList',
        // url : '../json/taskList.json',
        url : baseUrl+'/linkageCall/queryCallTaskPhoneMsg',
        request: {
            pageName: 'page' //页码的参数名称，默认：page
            ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
        where:{
            "taskId": taskId
        },response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            ,statusCode: 1 //成功的状态码，默认：0
            ,msgName: 'msg' //状态信息的字段名称，默认：msg
            ,countName: 'total' //数据总数的字段名称，默认：count
            ,dataName: 'records' //数据列表的字段名称，默认：data
        }
        ,loading: true
        ,cellMinWidth: 80
        ,cols : [[
            {field: 'sourceName', title: '客户类型'},
            {field: 'num', title: '数量', align:'center', templet: '#numTpl'},
            {title: '操作',templet:'#barDemo',align:"center",event: 'setNum'}
        ]],text: {
            none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        },done: function(res, curr, count){
            console.log(res);
            //得到当前页码
            console.log(curr);
            //得到数据总量
            console.log(count);
            uploadFun();
        }
    });

    //监听单元格事件
    table.on('tool(taskList)', function(obj){
        editTableRowObj = obj;
        var data = obj.data;
        if(obj.event === 'edit'){
            if(data.sourceName == '上传Excel文件'){
                return;
            }
            console.log(data.sourceName);
            layer.prompt({
                formType: 2
                ,title: '修改 ID 为 ['+ data.id +'] 的用户签名'
                ,value: data.num
            }, function(value, index){
                layer.close(index);
                //这里一般是发送修改的Ajax请求
                //同步更新表格和缓存对应的值
                obj.update({
                    num: value
                });
            });
        }else if(obj.event === 'down'){
            var $eleForm = $("<a href='"+baseUrl+"/file/联动call客excel模板.xlsx' download='联动call客excel模板.xlsx'></a>");
            $(document.body).append($eleForm);
            //提交表单，实现下载
            $eleForm[0].click();
        }
    });

    //上传EXCEL
    var uploadFun = function(){
        upload.render({
            elem: '.uploadBtn'
            ,url: baseUrl+'/linkageCall/uploadPhoneExcel'
            ,method : "post"
            ,accept: 'file' //普通文件
            ,multiple: true
            ,done: function(res){
               console.log(res);
               if(editTableRowObj!=null && editTableRowObj!=undefined){
                   selTaskSourceList.push(SelTaskSource.buildParam("UE",JSON.stringify(res.records)));
                   console.log(selTaskSourceList);
                   editTableRowObj.update({
                       num: res.records.length
                   });
                   $("#callNum").val(res.total);
               }
            }
        });
    };


    //格式化时间
    function filterTime(val){
        if(val < 10){
            return "0" + val;
        }else{
            return val;
        }
    }

    form.on('submit(add)', function(formData){
        if(clickSubmit==true){
            return;
        }
        clickSubmit = true;
        try{
            //弹出loading
            var load = layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
            var bo = verification(formData.form,null);
            if(bo){
                var submitData = formData.field;
                // submitData.customerId = customerId;
                delete submitData["file"];
                submitData.selTaskSourceStr = JSON.stringify(selTaskSourceList);//JSON.stringify(selTaskSourceList)
                console.log(submitData.selTaskSourceStr);
                saveData(submitData,load);
            }else{
                layer.close(load);
            }
        }catch (e){
            layer.msg("操作异常");
        }finally {
            clickSubmit = false;
        }
    });

    function saveData(submitData,load){
        console.log(submitData);
        $.ajax({
            type: "POST",
            url:  baseUrl+'/linkageCall/saveLinkageCallTask',
            dataType: 'json',
            data: submitData,
            success: function (data) {
                console.log(data);
                layer.close(load);
                if(data.code<=0){
                    layer.msg(data.msg);
                }else{
                    layer.msg("保存成功");
                    //关闭本窗体
                    setTimeout(function () {
                        tableIns.reload();
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    },1000);
                }
            },
            error: function () {
                layer.close(load);
                layer.msg("保存失败");
                return ;
            }
        });
    }

    $('#cancel').on('click',function () {
        currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引
        parent.layer.close(currentIndex);//执行关闭
    });


    //验证表单
    function verification(form,iframeWin) {
        var config = {
            verify: {
                required: [
                    /[\S]+/
                    , '必填项不能为空'
                ]
                , phone: [
                    /^1\d{10}$|^$/
                    , '请输入正确的手机号'
                ]
                , email: [
                    /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$|^$/
                    , '邮箱格式不正确'
                ]
                , url: [
                    /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/
                    , '链接格式不正确'
                ]
                , number: [
                    /^\d+$|^$/
                    , '只能填写数字'
                ]
                , date: [
                    /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$|^$/
                    , '日期格式不正确'
                ]
                , identity: [
                    /(^\d{15}$)|(^\d{17}(x|X|\d)$|^$)/
                    , '请输入正确的身份证号'
                ]
            }
        };
        formElem = $(form);
        var button = $(this), verify = config.verify, stop = null
            , DANGER = 'layui-form-danger',PROMPT='required_prompt', field = {}
            , verifyElem = formElem.find('*[lay-verify-zdy]') //获取需要校验的元素
            //, fieldElem = formElem.find('input,select,textarea') //获取所有表单域
            , checkedElem = formElem.find('*[data-required]') //获取复选框
            ,rangeElem = formElem.find('*[data-range]')//获取范围判断的区间值

        //开始校验
        layui.each(verifyElem, function (_, item) {
            var othis = $(this), tips = '';
            var arr = othis.attr('lay-verify-zdy').split(',');
            for (var i in arr) {
                var ver = arr[i];
                var value = othis.val(), isFn = typeof verify[ver] === 'function';
                if(ver == 'number'&&value==''){
                    value = 0;
                }
                othis.removeClass(DANGER);
                if (verify[ver] && (isFn ? tips = verify[ver](value, item) : !verify[ver][0].test(value))) {
                    layer.msg(tips || verify[ver][1], {
                        icon: 5
                        , shift: 6
                    });
                    //非移动设备自动定位焦点
                    if (!layui.device().android && !layui.device().ios) {
                        if(item.type=='text'){
                            item.focus();
                        }else if(item.type=="select-one"){
                            $(item).next("div").find("input").focus();
                            $(item).next("div").find("input").attr("readonly");
                        }
                    }
                    othis.addClass(DANGER);
                    return stop = true;
                }
            }
        });
        if (stop) return false;
        //返回序列化表单元素， JSON 数据结构数据。
        return true;
    };

});

